<template>
  <div class="add-btn">
    <el-dialog
      title="添加巡查项"
      :visible.sync="dialogVisible"
      width="1200px"
      :append-to-body="true"
      @close="closeDialog"
      :close-on-click-modal="false"
    >
      <div class="range">
        <div class="range-left">
          <div class="range-header">
            <div class="unit">
              <el-input
                placeholder="关键词模糊搜索"
                v-model="search_val"
                size="small"
                clearable
                style="width: 250px; margin-left: 15px"
              >
                <!-- @clear="onClearInput(2)" -->
                <template slot="append">
                  <el-button class="el-icon-search"></el-button>
                </template>
                <!-- @click="onClickInput(2)" -->
              </el-input>
            </div>
          </div>
          <div class="range-bottom">
            <el-tree
              ref="leftTree"
              :data="treeData_all"
              show-checkbox
              node-key="id"
              :props="defaultProps"
              default-expand-all
              @check-change="handleCheckChange"
            >
            </el-tree>
          </div>
        </div>

        <div class="range-middle">
          <div class="middle-icon">
            <i class="el-icon-arrow-right"></i>
          </div>
        </div>
        <div class="range-right">
          <div class="range-header"></div>
          <div class="install-table">
            <el-tree
              ref="rightTree"
              :data="treeData_ed"
              show-checkbox
              node-key="id"
              :props="defaultProps"
              default-expand-all
              :check-strictly="true"
            ></el-tree>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog" class="cancel-button"
          >取 消</el-button
        >
        <el-button
          size="small"
          @click="submit"
          v-preventReClick="1000"
          class="confirm-button"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import tableStyleMixin from "@mixin/table-style";
import Pagination from "@components/Pagination.vue";
import { mapState } from "vuex";
import { reqDeviceList, reqDetectorPage } from "@api/api.js";
import { reqPatrolItemPage } from "@api/patrol.js";
export default {
  props: ["orgId", "unitId", "buildingId", "floorId", "spaceId", "treeData"],
  mixins: [tableStyleMixin],
  components: { Pagination },
  data() {
    return {
      dialogVisible: false,
      loadingSearch: false,
      search_val: "",
      treeData_all: [],
      defaultProps: {
        children: "patrolCategorys", // 指定子节点字段
        label: (data) => data.name || data.content, // 动态决定 label
      },
      treeData_ed: [],
      limit: 10,
      page: 1,
      total: 0,
      batchDataList: [],
      choseDataDev: [],
      choseData1_copy: [],

      // 探测器
      deviceListTanceqi: [],
      batchDataList2: [],
      choseDataTCQ: [],
      choseData2_copy: [],
    };
  },
  computed: {
    ...mapState(["user"]),
  },
  watch: {
    async dialogVisible(val) {
      if (val) {
        if (this.treeData.length) {
          // 等待树数据加载完成
          await this.loadTreeData();
          const checkedKeys = this.collectNodeIds(this.treeData);
          this.$nextTick(() => {
            this.$refs.leftTree.setCheckedKeys(checkedKeys);
          });
        } else {
          await this.loadTreeData();
        }
        // this.treeData_all = this.treeData;
      }
    },
    treeData_ed: {
      handler(val) {
        this.$refs.rightTree.setCheckedKeys(
          this.$refs.leftTree.getCheckedKeys(true)
        );
      },
      deep: true,
    },
  },
  mounted() {
    // 初始化左边的树
    this.$nextTick(() => {
      this.$refs.leftTree = this.$refs.leftTree || null;
    });
  },
  methods: {
    // 异步加载树数据
    async loadTreeData() {
      const res = await reqPatrolItemPage(this.page, 99, {
        name: "",
        content: "",
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      let { rows, total } = res.data;
      this.treeData_all = rows;
    },

    // 收集节点ID
    collectNodeIds(data, idList = []) {
      if (!data) return idList;

      if (Array.isArray(data)) {
        data.forEach((item) => this.collectNodeIds(item, idList));
        return idList;
      }

      if (
        (data.patrolItemId && data.id) ||
        (data.patrolCategorys && !data.patrolCategorys.length)
      ) {
        idList.push(data.id);
      }
      // if (data.id) {
      //   idList.push(data.id);
      // }

      if (data.patrolCategorys && Array.isArray(data.patrolCategorys)) {
        data.patrolCategorys.forEach((child) =>
          this.collectNodeIds(child, idList)
        );
      }

      return idList;
    },

    // handleCheckChange() {
    //   const checkedKeys = this.$refs.leftTree.getCheckedKeys(true); // 获取所有选中节点的key
    //   this.treeData_ed = this.buildSelectedTree(this.treeData_all, checkedKeys);
    // },

    // 递归构建保留结构的树
    buildSelectedTree(nodes, checkedKeys) {
      return nodes
        .map((node) => {
          const newNode = { ...node };
          // 移除checked属性设置
          delete newNode.checked;

          if (newNode.patrolCategorys) {
            newNode.patrolCategorys = this.buildSelectedTree(
              newNode.patrolCategorys,
              checkedKeys
            );
          }

          // 仅判断是否保留节点（不处理选中状态）
          const shouldKeep =
            checkedKeys.includes(newNode.id) ||
            (newNode.patrolCategorys && newNode.patrolCategorys.length > 0);

          return shouldKeep ? newNode : null;
        })
        .filter(Boolean);
    },

    // 在handleCheckChange中添加重置选中状态逻辑
    handleCheckChange() {
      const checkedKeys = this.$refs.leftTree.getCheckedKeys(true);
      this.treeData_ed = this.buildSelectedTree(
        JSON.parse(JSON.stringify(this.treeData_all)),
        checkedKeys
      );

      // 新增：强制清除右侧所有选中状态
      this.$nextTick(() => {
        this.$refs.rightTree.setCheckedKeys([]);
      });
    },
    // 获取设备列表
    async getDataList() {
      // const res = await reqDeviceList(this.page, this.limit, {
      //   userId: this.user.userId,
      //   roleName: this.user.roleName,
      //   tenantId: this.user.tenantId,
      //   buildingId: this.buildingId,
      //   floorId: this.floorId,
      //   spaceId: this.spaceId,
      //   imei: this.search_val || "",
      // });
      // if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      // this.total = res.data.total;
      // this.deviceList = res.data.rows;
    },
    // 搜索
    async searchClick() {
      this.page = 1;
      this.limit = 10;
      this.loadingSearch = true;
      // if (this.activeName == "shebei") {
      //   await this.getDataList();
      // } else {
      //   await this.getDataListTannceqi();
      // }
      this.loadingSearch = false;
    },

    // 清空
    clearInput() {
      this.page = 1;
      this.limit = 10;
      // this.getDataList();
    },

    closeDialog() {
      // this.choseDataDev = [];
      // this.choseDataTCQ = [];
      // this.$refs.refTable.clearSelection();
      // this.$refs.refTableTanceqi.clearSelection();
      this.$refs.leftTree.setCheckedKeys([]);
      this.dialogVisible = false;
    },
    submit() {
      this.$emit("getDevices", this.treeData_ed);
      this.closeDialog();
    },
  },
};
</script>
<style lang="less" scoped>
@import url("~@views/style/tablePage.less");
@import url("../../../common.less");
// 范围样式
.range {
  display: flex;
  width: 100%;
  // margin-bottom: 20px;
  justify-content: center;
  .range-left {
    width: 46%;
    height: 420px;
    border: 1px solid @primaryBorderColor;
    .range-bottom {
      height: 340px;
      overflow: auto;
    }
  }

  .range-middle {
    width: 6%;
    display: flex;
    align-items: center;
    justify-content: center;
    .middle-icon {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      background-color: @primaryBgcolor2;
      display: flex;
      align-items: center;
      justify-content: center;
      .el-icon-arrow-right {
        font-size: 20px;
        color: @primaryBorderColor2;
      }
    }
  }

  .range-right {
    width: 46%;
    height: 420px;
    border: 1px solid @primaryBorderColor;
  }
  .range-header {
    height: 60px;
    border-bottom: 1px solid @primaryBorderColor;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    box-sizing: border-box;
    padding: 0 10px;
  }
}
::v-deep .el-tabs--border-card > .el-tabs__header .el-tabs__item.is-active {
  color: #7367f0;
}

::v-deep .el-tabs__header .el-tabs__item.is-active {
  border-bottom: 1px solid #7367f0;
}

/* 修改鼠标移入时的样式 */
::v-deep .el-tabs__item:hover {
  color: #7367f0 !important;
}

::v-deep .el-tabs--border-card {
  border: none !important;
  box-shadow: none !important;
}

::v-deep .el-checkbox__inner {
  background-color: transparent !important;
  border: 1px solid @primaryBorder !important;
}
// 多选框
.el-checkbox {
  color: @primaryThemeTxtColor2 !important;
}

// 单选框
.el-radio__inner {
  background: none !important;
}

::v-deep .el-radio__input.is-disabled .el-radio__inner {
  background: #e1e2e6 !important;
}

::v-deep .el-tree {
  height: calc(100% - 66px);
  background: @primaryHeaderBgcolor;
  border-radius: 0 0 0 6px;
  box-sizing: border-box;
  padding: 12px 10px;
  color: @primaryThemeTxtColor;
}

::v-deep .el-tree-node__content:hover {
  background: @paginationBgcolor !important;
  border-radius: 4px;
}

::v-deep .el-tree-node.is-current > .el-tree-node__content {
  background-color: #7367f0 !important;
  border-radius: 4px;
}

::v-deep .is-current > .el-tree-node__content > .el-tree-node__label {
  color: #f0f0f0;
}
</style>
